<template>
  <div class="app-container">
    <div
      style="width: 120%;height: 40px;background-color:#eaeaea; margin: -10px 0 10px -15px;font-weight: bold;font-size: 14px;line-height: 40px">
      {{ research.sname }}
    </div>
    <el-row style="float: left">
      <el-col style="font-weight: 800; font-size: 16px; margin: 0; padding: 0;">受试者列表</el-col>
      <el-col style="font-size: 12px; color: #666; margin: 0; padding: 0;">共 {{ testerList.length }} 条记录</el-col>
    </el-row>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px"
             style="float: right">
      <el-form-item label="所在医院" prop="hospName">
        <el-input v-model="queryParams.hospName" placeholder="请输入所在医院" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="受试者姓名" prop="name" label-width="100px">
        <el-input v-model="queryParams.name" placeholder="请输入受试者姓名" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="住院号" prop="hospitalizationNumber">
        <el-input v-model="queryParams.hospitalizationNumber" placeholder="请输入住院号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">
          批量导出
        </el-button>
      </el-form-item>
    </el-form>

    <!--  表单列表  -->
    <el-table v-loading="loading" :data="testerList" @selection-change="handleSelectionChange" style="font-size: 12px;">
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column label="医院" align="center" prop="hospName" width="180"/>
      <el-table-column label="受试者姓名" align="center" prop="name" width="120"/>
      <el-table-column label="住院号" align="center" prop="hospitalizationNumber" width="100"/>
      <el-table-column label="科室" align="center" prop="department" width="100"/>
      <el-table-column label="病区" align="center" prop="ward" width="100"/>
      <el-table-column label="床号" align="center" prop="badNumber" width="100"/>
      <el-table-column
        :filters="[
        {text: '实验组', value: '实验组'},
        {text: '对照组', value: '对照组'},
        {text: '暂未入组', value: '暂未入组'},
        {text: '无法入组', value: '无法入组'},
      ]"
        :filter-method="filterGroupName"
        label="研究组别"
        align="center"
        prop="groupName"
        width="100"
      />
      <el-table-column
        :filters="[
        {text: '未开始', value: '未开始'},
        {text: '待完善', value: '待完善'},
        {text: '已完成', value: '已完成'},
        {text: '已提交', value: '已提交'}
      ]"
        :filter-method="filterCrf"
        label="状态" align="center" prop="crf" width="100"/>

      <el-table-column label="术前筛选期 (V0)" align="center" width="90">
        <template slot-scope="scope">
          <div class="circle-container">
            <img :src="getCircleImage(scope.row.szero)" alt="status icon"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="手术当天 (V1)" align="center" width="80">
        <template slot-scope="scope">
          <div class="circle-container">
            <img :src="getCircleImage(scope.row.sone)" alt="status icon"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="术后第一天 (V2)" align="center" width="80">
        <template slot-scope="scope">
          <div class="circle-container">
            <img :src="getCircleImage(scope.row.stwo)" alt="status icon"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="术后第二天 (V3)" align="center" width="80">
        <template slot-scope="scope">
          <div class="circle-container">
            <img :src="getCircleImage(scope.row.sthree)" alt="status icon"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="术后第三天 (V4)" align="center" width="80">
        <template slot-scope="scope">
          <div class="circle-container">
            <img :src="getCircleImage(scope.row.sfour)" alt="status icon"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template template slot-scope="scope">
          <el-button style="padding: 10px 5px;" size="mini" type="success" @click="crfTrans(scope.row.id, 0)">查
            看
          </el-button>
          <el-button style="padding: 10px 5px;" size="mini" type="primary" @click="crfTrans(scope.row.id, 1)">编
            辑
          </el-button>
          <el-button style="padding: 10px 5px;" size="mini" type="danger" @click="handleDelete(scope.row)">删 除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <div style="display: flex; justify-content: flex-start; align-content: center">
      <span style="font-weight: 500; font-size: 16px"><img src="@/icon/circle-full.png"
                                                           style="vertical-align:middle; margin: 0 10px;" alt=""
                                                           srcset="">表单已经填写</span>
      <span style="font-weight: 500; font-size: 16px"><img src="@/icon/circle-half.png"
                                                           style="vertical-align:middle; margin: 0 10px" alt=""
                                                           srcset="">表单已经填写</span>
      <span style="font-weight: 500; font-size: 16px"><img src="@/icon/circle-empty.png"
                                                           style="vertical-align:middle; margin: 0 10px" alt=""
                                                           srcset="">表单已经填写</span>
    </div>


    <!-- 添加或修改受试者，存放受试者详细信息。对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="医院ID" prop="hospitalId">
          <el-input v-model="form.hospitalId" placeholder="请输入医院ID"/>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="住院号" prop="hospitalizationNumber">
          <el-input v-model="form.hospitalizationNumber" placeholder="请输入住院号"/>
        </el-form-item>
        <el-form-item label="科室" prop="department">
          <el-input v-model="form.department" placeholder="请输入科室"/>
        </el-form-item>
        <el-form-item label="病区" prop="ward">
          <el-input v-model="form.ward" placeholder="请输入病区"/>
        </el-form-item>
        <el-form-item label="床号" prop="badNumber">
          <el-input v-model="form.badNumber" placeholder="请输入床号"/>
        </el-form-item>
        <el-form-item label="CRF提交" prop="crf">
          <el-input v-model="form.crf" placeholder="请输入CRF提交状态"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listTester, getTester, delTester, addTester, updateTester} from "@/api/tester/tester";
import {listCompletion} from "@/api/completion/completion";
import {listCrfFour} from "@/api/crfFour/crfFour";
import {listCrfThree} from "@/api/crfThree/crfThree";
import {listCrfTwo} from "@/api/crfTwo/crfTwo";
import {listCrfOne} from "@/api/crfOne/crfOne";
import {listCrfZero} from "@/api/crfZero/crfZero";

import {getlistById} from "@/api/system/research";
import * as XLSX from 'xlsx';

export default {
  name: "Tester",
  data() {
    return {
      ids: [], // 用于存放选中的受试者 ID
      zeroData: {}, // 存放 V0 阶段数据
      oneData: {},  // 存放 V1 阶段数据
      twoData: {},  // 存放 V2 阶段数据
      threeData: {},  // 存放 V3 阶段数据
      fourData: {},  // 存放 V4 阶段数据
      completionData: {},  // 存放 V5 Completion 阶段数据
      testerName: "", // 用于保存受试者姓名
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 受试者，存放受试者详细信息。表格数据
      testerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: this.$route.query.id
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      research: [],
    };
  },
  created() {
    this.getList();
    getlistById(this.$route.query.id).then(res => {
      this.research = res;
      console.log(this.research);
    });
    // 检查 URL 中是否提供了 id
    if (this.$route.query.id != null) {
      // 获取单个受试者详细信息
      getTester(this.$route.query.id).then(res => {
        if (res && res.data && res.data.name) {
          this.zeroData.fullName = res.data.name;  // 保存中文名字
          this.testerName = res.data.name;         // 保存中文名字用于展示
        }
      });

      // 获取 V0 数据
      listCrfZero(this.$route.query.id).then(res => {
        console.log(res);
        if (res) {
          this.zeroData = res;
        }
      });

      // 获取 V1 数据
      listCrfOne(this.$route.query.id).then(res => {
        console.log(res);
        if (res) {
          this.oneData = res;
        }
      });

      // 获取 V2 数据
      listCrfTwo(this.$route.query.id).then(res => {
        console.log(res);
        if (res) {
          this.twoData = res;
        }
      });

      // 获取 V3 数据
      listCrfThree(this.$route.query.id).then(res => {
        console.log(res);
        if (res) {
          this.threeData = res;
        }
      });

      // 获取 V4 数据
      listCrfFour(this.$route.query.id).then(res => {
        console.log(res);
        if (res) {
          this.fourData = res;
        }
      });

      // 获取 Completion 数据 (V5)
      listCompletion(this.$route.query.id).then(res => {
        console.log(res);
        if (res) {
          this.completionData = res;
        }
      });
    }
  },


  methods: {
    // 赛选研究组别
    filterGroupName(value, row) {
      return row.groupName === value;
    },
    // 筛选状态
    filterCrf(value, row) {
      return row.crf === value;
    },

    // 获取图标路径方法
    getCircleImage(value) {
      if (value === 1) return require('@/icon/circle-full.png'); // 满
      if (value === 2) return require('@/icon/circle-half.png'); // 半
      else return require('@/icon/circle-empty.png');                 // 空
    },
    /** 查询受试者，存放受试者详细信息。列表 */
    crfTrans(id, f) {
      this.$router.push('/CRF?id=' + id + '&sid=' + this.$route.query.id + '&f=' + f);
    },
    getList() {
      this.loading = true;
      listTester(this.queryParams).then(response => {
        this.testerList = response.rows;
        for (var i in this.testerList) {
          if (this.testerList[i] && typeof this.testerList[i].crf !== 'undefined') {
            if (this.testerList[i].crf === 'true') {
              this.testerList[i].crf = "已完成";
            } else {
              this.testerList[i].crf = "未提交";
            }
          }
        }
        console.log(this.testerList);
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        department: null,
        hospitalizationNumber: null,
        ward: null,
        badNumber: null,
        hospitalId: null,
        groupId: null,
        name: null,
        random: null,
        crf: null,
        resTester: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加受试者，存放受试者详细信息。";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getTester(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改受试者，存放受试者详细信息。";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTester(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTester(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除受试者，存放受试者详细信息。编号为"' + ids + '"的数据项？').then(function () {
        return delTester(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */

    handleExport() {
      if (this.ids.length === 0) {
        this.$message.warning("请先勾选需要导出的受试者数据");
        return;
      }

      // 使用 list 方法并行获取每个阶段的数据
      const promises = this.ids.map(id => {

        return Promise.all([
          listCrfZero( id ),     // 确保 id 被传递为对象的属性
          listCrfOne(id ),      // 同样修正其他 API 调用
          listCrfTwo( id ),
          listCrfThree( id ),
          listCrfFour(id ),
          listCompletion(id )
        ]).then(responses => {
          return {
            zeroData: responses[0],      // V0 数据
            oneData: responses[1],       // V1 数据
            twoData: responses[2],       // V2 数据
            threeData: responses[3],     // V3 数据
            fourData: responses[4],      // V4 数据
            completionData: responses[5] // V5 数据
          };
        });
      });

      Promise.all(promises).then(responses => {
        console.log(responses[0])
        const detailedData = this.ids.map((id, index) => {
          return {
            // zeroData: responses[0].data.find(item => item.testerId === id),  // V0 数据
            // oneData: responses[1].data.find(item => item.testerId === id),   // V1 数据
            // twoData: responses[2].data.find(item => item.testerId === id),   // V2 数据
            // threeData: responses[3].data.find(item => item.testerId === id), // V3 数据
            // fourData: responses[4].data.find(item => item.testerId === id),  // V4 数据
            // completionData: responses[5].data.find(item => item.testerId === id) // V5 数据
            zeroData: responses[0].zeroData,  // V0 数据
            oneData: responses[0].oneData,   // V1 数据
            twoData: responses[0].twoData,   // V2 数据
            threeData: responses[0].threeData, // V3 数据
            fourData: responses[0].fourData,  // V4 数据
            completionData: responses[0].completionData // V5 数据
          };
        });

        this.exportToExcel(detailedData);
      }).catch(err => {
        console.error('Error during data fetching:', err);
        this.$message.error('获取数据时发生错误');
      });
    },


    exportToExcel(detailedData) {
      const XLSX = require('xlsx');
      const wb = XLSX.utils.book_new();

      detailedData.forEach((data, index) => {
        const wsData = [
          ["患者v0表单", "值"],
          ["Tester ID", data.zeroData.testerId],
          ["Full Name", data.zeroData.fullName],
          ["In Hospital", data.zeroData.inHospital],
          ["Height", data.zeroData.height],
          ["Weight", data.zeroData.weight],
          ["Diagnosis", data.zeroData.diagnosis],
          ["Static Score", data.zeroData.staticScore],
          ["Activity Score", data.zeroData.actScore],
          ["Heart Rate", data.zeroData.heartRate],
          ["Systolic Pressure", data.zeroData.sysPres],
          ["Diastolic Pressure", data.zeroData.diasPres],
          ["Breath", data.zeroData.breath],
          ["Temperature", data.zeroData.temp],
          ["Incl One", data.zeroData.inclOne],
          ["Incl Two", data.zeroData.inclTwo],
          ["Incl Three", data.zeroData.inclThree],
          ["Incl Four", data.zeroData.inclFour],
          ["Incl Five", data.zeroData.inclFive],
          ["Join Group", data.zeroData.joinGroup],
          ["Status", data.zeroData.status],


        ];
        const wsData2 = [
          ["患者v1表单", "值"],
          ["Trial Group", data.oneData.trialGroup],
          ["Surgery Date", data.oneData.surgeryDate],
          ["Surgery Name", data.oneData.surgeryName],
          ["Surgery Start Time", data.oneData.surgeryStartTime],
          ["Surgery End Time", data.oneData.surgeryEndTime],
          ["ASA Grade", data.oneData.asaGrade],
          ["Anesthesia Method", data.oneData.anesthesiaMethod],
          ["Post-op Infiltration", data.oneData.postOpInfiltration],
          ["Post-op Pain Relief", data.oneData.postOpPainRelief],
          ["2h Pain Rest", data.oneData.painAssessment2hRest],
          ["2h Pain Activity", data.oneData.painAssessment2hActivity],
          ["4h Pain Rest", data.oneData.painAssessment4hRest],
          ["4h Pain Activity", data.oneData.painAssessment4hActivity],
          ["6h Pain Rest", data.oneData.painAssessment6hRest],
          ["6h Pain Activity", data.oneData.painAssessment6hActivity],
          ["8h Pain Rest", data.oneData.painAssessment8hRest],
          ["8h Pain Activity", data.oneData.painAssessment8hActivity],
          ["Status", data.oneData.status],
        ];
        const wsData3 = [
          ["患者v2表单", "值"],
          ["Visit Date", data.twoData.visitDate],
          ["NRS Rest", data.twoData.nrsRest],
          ["NRS Activity", data.twoData.nrsActivity],
          ["Sleep Satisfaction", data.twoData.sleepSatis],
          ["Bowel Check", data.twoData.bowelCheck],
          ["Bowel Hurt", data.twoData.bowelHurt],
          ["Bowel Time", data.twoData.bowelTime],
          ["Bed Time", data.twoData.bedTime],
          ["Bed Hurt", data.twoData.bedHurt],
          ["Out of Bed", data.twoData.outBed],
          ["Wounds", data.twoData.wounds],
          ["Qu Dose", data.twoData.quDose],
          ["Qu Time", data.twoData.quTime],
          ["Qu Maduo", data.twoData.qumaduo],
          ["Analgesic Use", data.twoData.analUse],
          ["Adverse Event One", data.twoData.adverOne],
          ["Adverse Event Two", data.twoData.adverTwo],
          ["Status", data.twoData.status],
        ];
        const wsData4 = [
          ["患者v3表单", "值"],
          ["Visit Date", data.threeData.visitDate],
          ["NRS Rest", data.threeData.nrsRest],
          ["NRS Activity", data.threeData.nrsActivity],
          ["Sleep Satisfaction", data.threeData.sleepSatis],
          ["Bowel Check", data.threeData.bowelCheck],
          ["Bowel Hurt", data.threeData.bowelHurt],
          ["Bowel Time", data.threeData.bowelTime],
          ["Bed Time", data.threeData.bedTime],
          ["Bed Hurt", data.threeData.bedHurt],
          ["Out of Bed", data.threeData.outBed],
          ["Wounds", data.threeData.wounds],
          ["Adverse Event One", data.threeData.adverOne],
          ["Adverse Event Two", data.threeData.adverTwo],
          ["Status", data.threeData.status],
        ];
        const wsData5 = [
          ["患者v4表单", "值"],
          ["Visit Date", data.fourData.visitDate],
          ["NRS Rest", data.fourData.nrsRest],
          ["NRS Activity", data.fourData.nrsActivity],
          ["Sleep Satisfaction", data.fourData.sleepSatis],
          ["Bowel Check", data.fourData.bowelCheck],
          ["Bowel Hurt", data.fourData.bowelHurt],
          ["Bowel Time", data.fourData.bowelTime],
          ["Bed Time", data.fourData.bedTime],
          ["Bed Hurt", data.fourData.bedHurt],
          ["Out of Bed", data.fourData.outBed],
          ["Wounds", data.fourData.wounds],
          ["Adverse Event One", data.fourData.adverOne],
          ["Adverse Event Two", data.fourData.adverTwo],
          ["Wound Healing", data.fourData.woundHeal],
          ["Status", data.fourData.status],
        ];
        const wsData6 = [
          ["患者研究结束表单", "值"],
          ["Surgery Date", data.completionData.surgeryDate],
          ["Study Completed", data.completionData.studyCompleted],
          ["Reason Not Completed", data.completionData.reasonNotCompleted],
          ["Discharge Date", data.completionData.dischargeDate],
          ["Post-op Hospital Days", data.completionData.postOpHospitalDays],
          ["Status", data.completionData.status],
        ];

        const ws = XLSX.utils.aoa_to_sheet(wsData);
        const ws2 = XLSX.utils.aoa_to_sheet(wsData2);
        const ws3 = XLSX.utils.aoa_to_sheet(wsData3);
        const ws4 = XLSX.utils.aoa_to_sheet(wsData4);
        const ws5 = XLSX.utils.aoa_to_sheet(wsData5);
        const ws6 = XLSX.utils.aoa_to_sheet(wsData6);
        XLSX.utils.book_append_sheet(wb, ws, `受试者_${index + 1} 的sheet1`);
        XLSX.utils.book_append_sheet(wb, ws2, `sheet2`);
        XLSX.utils.book_append_sheet(wb, ws3, `sheet3`);
        XLSX.utils.book_append_sheet(wb, ws4, `sheet4`);
        XLSX.utils.book_append_sheet(wb, ws5, `sheet5`);
        XLSX.utils.book_append_sheet(wb, ws6, `sheet6`);
      });

      XLSX.writeFile(wb, `受试者详细数据_${new Date().toISOString().slice(0, 10)}.xlsx`);
    }
  }
};
</script>

<style scoped>
.app-container {
  font-size: 12px;
}

.circle-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.circle-full {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: green;
  border: 2px solid green;
}

.circle-half {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: green;
  position: relative;
  border: 2px solid green;
}

.circle-half::before {
  content: '';
  position: absolute;
  top: 0;
  left: 40%;
  width: 60%;
  height: 100%;
  background: white;
  border-radius: 0 50% 50% 0;
}

.circle-empty {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 2px solid green;
}
</style>
